package states

import (
	"go_server/game_server/dao/count_down_dao"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/zinx/ziface"
	"go_server/zinx/znet"
)

type SaveTimeLineApi struct {
	znet.BaseRouter
}

// 保存timeline节点
func (*SaveTimeLineApi) Handle(request ziface.IRequest) {
	msg := &pb.SaveTimeLineC2S{}
	if !util.PBParseRet(request, msg) {
		return
	}

	conn := request.GetConnection()
	roleId := ServiceObj.GetRoleId(request)

	fields := []string{"event_list"}
	row := count_down_dao.GetCountDownByRoleId(roleId, fields)

	eventList := make([]int32, 0)
	if row != nil && row.EventList != nil {
		eventList = row.EventList
	}
	
	var update = true

	if len(eventList) > 0 {
		eventSet := util.NewSet[int32]()
		eventSet.AddValue(eventList)
		if !eventSet.Contains(msg.EventId) { // 没有完成过
			eventList = append(eventList, msg.EventId)
		} else {
			update = false
		}
	} else {
		eventList = append(eventList, msg.EventId)
	}

	res := &pb.SaveTimeLineS2C{
		EventList: eventList,
	}

	// 优先返回下行
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_SaveTimeLine), res)

	if update {
		countDown := count_down_dao.CountDown{
			RoleId:    roleId,
			EventList: eventList,
		}
		count_down_dao.UpdateCountDown(&countDown, fields)
	}
}
